import gtk
import os.path
import mlib_utils
import xmmsclient
import xmmsclient.collections
from xmmsclient.collections import *


class BroadcastManager:
    iters_pool = []
    
    def __init__(self, mlib, xmms2):
        iconview = mlib.get_widget("iconview1")
        model = iconview.get_model()
        self.mlib = mlib
        self.model = model
        self.iconview = iconview
        self.xmms2 = xmms2
        
        xmms2.coll_query_infos(
            Intersection(
                Universe(), 
                Has(Universe(), field="artist"),
                Has(Universe(), field="album"), 
                Has(Universe(), field="picture_front")), 
            ("artist", "album", "picture_front"), 
            leng=0,
            order=None,
            groupby=["artist", "album"],
            cb=self.insert_entries)

    def insert_entries(self, res):
        if res.iserror():
            print "[BroadcastManager] Could not insert entries"
            return
        all_entries = res.value()
        current_artist = None
        current_album = None
        entry = all_entries.pop(0)
        artist = entry["artist"]
        album = entry["album"]
        hash = entry["picture_front"]
        markup = mlib_utils.mark(artist, album)
        current_album = self.model.append([None, markup, album])
        self.iters_pool.append(current_album)
        self.xmms2.bindata_retrieve(hash, cb=self.add_cover)
        for e in all_entries:
            artist = e["artist"]
            album = e["album"]
            hash = e["picture_front"]
            markup = mlib_utils.mark(artist, album)
            current_album = self.model.append([None, markup, album])
            self.iters_pool.append(current_album)
            self.xmms2.bindata_retrieve(hash, cb=self.add_cover)

    def add_cover(self, res):
        if res.iserror():
            print "[BroadcastManager] Could not insert entries"
            self.iters_pool.pop(0)
            return
        iter = self.iters_pool.pop(0)
        cover = res.value()
        loader = gtk.gdk.PixbufLoader()
        loader.set_size(mlib_utils.THUMBNAILS_SIZE, 
        mlib_utils.THUMBNAILS_SIZE)
        loader.write(cover)
        loader.close()
        pb = loader.get_pixbuf()
        self.model.set(iter, 0, pb)
